import { Component, ViewChild, ElementRef } from '@angular/core';
import {
  IonicPage,
  NavController,
  Slides,
  ToastController,
  AlertController,
  Platform,
  App,
  NavParams,
  Keyboard
} from 'ionic-angular';
import { LoginApi } from '../../api/login/LoginApi';
import { AddressApi } from "../../api/login/AddressApi";
import { BarcodeScanner } from '@ionic-native/barcode-scanner';
import { Geolocation } from '@ionic-native/geolocation';
import { Network } from "@ionic-native/network";


@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  @ViewChild(Slides) slides: Slides;
  userName: string;
  pwd: string;
  logininfo: string[];

  private positionId: string = "0";//初始化一个positionId,如果未找到维护地点打尺,默认给0

  //控制硬件返回按钮是否触发，false
  public backButtonPressed: boolean = false;
  //注册事件开启,true
  public backButtontag: boolean = false;

  ionViewWillEnter() {
    this.platform.registerBackButtonAction(() => {
      //registerBackButtonAction是系统自带的方法
      //获取NavController
      let activeNav: NavController = this.app.getActiveNavs()[0];
      //如果有键盘 关闭键盘
      if (this.keyboard.isOpen()) {
        this.keyboard.close();
      }
      //如果可以返回上一页，则执行pop
      else if (activeNav.canGoBack()) {
        //如果是登出操作进入的主页则依旧执行退出方法
        if (this.backButtontag) {
          this.showExit();
        } else {
          this.navCtrl.pop();
        }
      } else {
        this.showExit();
      }
    });

    this.slides.autoplayDisableOnInteraction = false;
  }

  ionViewWillLeave() {
    this.slides.stopAutoplay();
    this.backButtontag = false;
  }

  ionViewDidLoad() {
    if (this.network.type === 'unknown') {
      this.showMsg("未知的网络环境，请注意！")
    } else if (this.network.type === 'none') {
      let alert = this.alertCtrl.create({
        title: '是否进入离线操作？',
        message: '当前无网络连接！',
        buttons: ['取消',
          {
            text: '确定',
            handler: data => {
              //点击确定,跳转到离线操作页面
              this.navCtrl.push('OfflineOperation');
            }
          }]
      });
      alert.present();
    } else if (this.network.type === '2g' || this.network.type === '3g') {
      let alert = this.alertCtrl.create({
        title: '是否进入离线操作？',
        message: '当前使用' + this.network.type + '网络，网络环境不佳！',
        buttons: ['取消',
          {
            text: '确定',
            handler: data => {
              //点击确定,跳转到离线操作页面
              this.navCtrl.push('OfflineOperation');
            }
          }]
      });
      alert.present();
    } else {
      this.showMsg("当前使用" + this.network.type + "网络，网络环境良好。")
    }

  }

  constructor(private network: Network, private geolocation: Geolocation, public keyboard: Keyboard, public params: NavParams, private app: App, public platform: Platform, private ele: ElementRef, private barcodeScanner: BarcodeScanner, public navCtrl: NavController, public loginApi: LoginApi, private addressApi: AddressApi, private toastCtrl: ToastController, private alertCtrl: AlertController) {
    this.backButtontag = params.get("backButtontag");

  }



  //退出应用方法
  private showExit(): void {
    //如果为true，退出
    if (this.backButtonPressed) {
      this.platform.exitApp();
    } else {
      //第一次按，弹出Toast
      this.toastCtrl.create({
        message: '再按一次退出应用',
        duration: 2000,
        position: 'middle'
      }).present();
      //标记为true
      this.backButtonPressed = true;
      //两秒后标记为false，如果退出的话，就不会执行了
      setTimeout(() => this.backButtonPressed = false, 2000);
    }
  }


  //修复轮播BUG
  fix() {
    if (this.slides.getActiveIndex() == 4) {
      setTimeout(() => {
        this.slides.slideTo(1, 2000);
      }, 2000);
    } else if (this.slides.getActiveIndex() == 5) {
      this.slides.slideTo(1, 2000);
    }

  }

  doLogin() {
    const http$ = this.loginApi.auth(this.userName, this.pwd);
    http$.subscribe((val: any) => {
      let loginResult = JSON.parse(val);
      if (loginResult.state) {
        this.showMsg("登陆成功,正在进行GPS定位...");
        localStorage.setItem("token", loginResult.token);
        localStorage.setItem("userInfo", loginResult.userInfo);
        this.gpsAddress();
      } else {
        this.showMsg(loginResult.msg);
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
      }
    });
  }


  scanLogin() {
    this.barcodeScanner.scan({ showTorchButton: true, resultDisplayDuration: 0 }).then((data) => {
      if (data.text.length != 0) {
        this.logininfo = data.text.split("丨");
        if (this.logininfo.length == 2) {
          this.userName = this.logininfo[0];
          this.pwd = this.logininfo[1];
          this.ele.nativeElement.querySelector("#dologin").click();
        } else {
          this.showMsg("请扫描正确的二维码!");
        }
      } else {
        this.showMsg("请扫描正确的二维码!");
      }
    }, (err) => {
      this.showMsg("扫描出现异常" + err);
    });
  }

  /**
   * 进行gps定位，去服务器获取最近的位置列表供用户选择
   */
  gpsAddress() {
    // this.geolocation.getCurrentPosition().then((resp) => {
    //   this.addressApi.getAddress(String(resp.coords.latitude), String(resp.coords.longitude)).subscribe(res => {
    //     console.log(String(resp.coords.latitude));
    //     console.log(String(resp.coords.longitude));
    //     let result = JSON.parse(res);
    //     if (result.state) {
    //       this.showMsg("定位成功,正在链接服务器获取最近位置信息...");
    //       let addresses = result.data;
    //       this.doSelectAddress(addresses);
    //     } else {
    //       /**
    //        * 登陆成功,10公里范围内未查询到位置信息
    //        */
    //       //this.showMsg("定位成功,"+result.msg);
    //       let alert = this.alertCtrl.create({
    //         title: '是否此地检验货物？',
    //         message: "定位成功," + result.msg,
    //         buttons: ['取消',
    //           {
    //             text: '确定',
    //             handler: data => {
    //               //点击确定,跳转到货物检测扫描界面
    //               this.navCtrl.push("RuleScan", { "positionId": this.positionId });
    //             }
    //           }]
    //       });
    //       alert.present();
    //     }
    //   })
    // }).catch(error => {
    //   console.log('Error getting location', error);
    // });

    var options = {
      enableHighAccuracy: true,  // 是否使用 GPS
      maximumAge: 60000,         // 缓存时间
      timeout: 27000,            // 超时时间
      coorType: 'bd09ll'         // 默认是 gcj02，可填 bd09ll 以获取百度经纬度用于访问百度 API
    }
    navigator.geolocation.getCurrentPosition((position: any) => {
      // console.log(<string>position.coords.latitude);
      // console.log(<string>position.coords.longitude);
      if (<string>position.coords.latitude == "5e-324" || <string>position.coords.longitude == "5e-324" || <string>position.coords.latitude == "4.9E-324" || <string>position.coords.longitude == "4.9E-324") {
        const alert = this.alertCtrl.create({
          title: '定位失败!，请检查位置功能与权限是否打开！',
          subTitle: '位置功能》》设置-位置-开启  位置权限》》设置-权限-应用-定位—开启',
          buttons: ['确定']
        });
        alert.present();
        return;
      }
      this.addressApi.getAddress(<string>position.coords.latitude, <string>position.coords.longitude).subscribe(res => {
        let result = JSON.parse(res);
        if (result.state) {
          this.showMsg("定位成功,正在链接服务器获取最近位置信息...");
          let addresses = result.data;
          this.doSelectAddress(addresses);
        } else {
          /**
           * 登陆成功,10公里范围内未查询到位置信息
           */
          //this.showMsg("定位成功,"+result.msg);
          let alert = this.alertCtrl.create({
            title: '是否此地检验货物？',
            message: "定位成功," + result.msg,
            buttons: ['取消',
              {
                text: '确定',
                handler: data => {
                  //点击确定,跳转到货物检测扫描界面
                  this.navCtrl.push("RuleScan", { "positionId": this.positionId });
                }
              }]
          });
          alert.present();
        }
      });
    }, (error: any) => {
      this.showMsg(error);
    }, options);
  }

  /**
   * 用户进行位置选择，选择完毕后进入下一个页面：项目计划列表页。
   * @param {object[]} addresses
   */
  doSelectAddress(addresses: object[]) {
    let alert = this.alertCtrl.create();

    alert.setTitle('请选择您所在的位置');
    for (var index in addresses) {
      let item: any = addresses[index];
      alert.addInput({
        type: 'radio',
        label: item.positionName,
        value: item.id,
        checked: parseInt(index) == 0 ? true : false
      });
    }

    alert.addButton({
      text: '确定',
      handler: (data: any) => {
        this.navCtrl.setRoot('ProjectPlan', { "position": data, "userName": this.userName }, {
          animate: true,
          direction: 'forward'
        });
      }
    });
    alert.present();
  }

  showMsg(msg: string) {
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
  }

  goOffline() {
    this.navCtrl.push('OfflineOperation');
  }

}
